package com.yunxin.admin.system.api.core.user;

import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.common.result.PageResult;
import com.yunxin.core.application.command.user.UserInfoPageCommand;
import com.yunxin.core.application.dto.user.UserInfoPageDTO;
import com.yunxin.core.application.service.UserQueryAdminService;
//import com.yunxin.statistics.application.dto.UserAllocationStatisticsListDTO;
//import com.yunxin.statistics.application.service.StatisticsQueryAdminService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zero°
 * @since 2023-06-08
 */
@Tag(name = "71.用户管理")
@Slf4j
@RestController
@RequestMapping("/core/v1/user")
@RequiredArgsConstructor
public class UserController {

    private final UserQueryAdminService userQueryAdminService;

//    private final StatisticsQueryAdminService statisticsQueryAdminService;

    @Operation(summary = "分页查询用户列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/userPageQuery")
    public PageResult<UserInfoPageDTO> userPageQuery(@Validated @RequestBody UserInfoPageCommand command) {
//        PageResult<UserInfoPageDTO> result = userQueryAdminService.userPageQuery(command);
//        List<UserInfoPageDTO> list = result.getData().getList();
//        if (list.isEmpty()) {
//            return result;
//        }
//        Set<String> userCodes = list.stream().map(UserInfoPageDTO::getUserCode).collect(Collectors.toSet());
//        //查询分配次数
//        List<UserAllocationStatisticsListDTO> userAllocationStatisticsList = statisticsQueryAdminService.listUserAllocationStatistics(userCodes);
//        Map<String, UserAllocationStatisticsListDTO> userAllocationStatisticsMap = userAllocationStatisticsList.stream().collect(Collectors.toMap(UserAllocationStatisticsListDTO::getUserCode, Function.identity()));
//        list.forEach(x -> {
//            UserAllocationStatisticsListDTO userAllocationStatisticsListDTO = userAllocationStatisticsMap.get(x.getUserCode());
//            if (Objects.nonNull(userAllocationStatisticsListDTO)) {
//                x.setAllocationCount(userAllocationStatisticsListDTO.getAllocationCount());
//                x.setAllocationTime(userAllocationStatisticsListDTO.getAllocationLatestTime());
//                x.setTwoUV(userAllocationStatisticsListDTO.getTwoUV());
//            }
//        });
//        return PageResult.success(list, result.getData().getTotal());
        return userQueryAdminService.userPageQuery(command);
    }


    @Operation(summary = "导出用户列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/export")
    public ResponseEntity<byte[]> export (@Validated @RequestBody UserInfoPageCommand command) throws IOException {

//        PageResult<UserInfoPageDTO> result = userQueryAdminService.userPageQuery(command);
//        List<UserInfoPageDTO> list = result.getData().getList();
//        if (list.isEmpty()) {
//            return null;
//        }
//        Set<String> userCodes = list.stream().map(UserInfoPageDTO::getUserCode).collect(Collectors.toSet());
//        List<UserAllocationStatisticsListDTO> userAllocationStatisticsList = statisticsQueryAdminService.listUserAllocationStatistics(userCodes);
//        Map<String, UserAllocationStatisticsListDTO> userAllocationStatisticsMap = userAllocationStatisticsList.stream().collect(Collectors.toMap(UserAllocationStatisticsListDTO::getUserCode, Function.identity()));
//        list.forEach(x -> {
//            UserAllocationStatisticsListDTO userAllocationStatisticsListDTO = userAllocationStatisticsMap.get(x.getUserCode());
//            if (Objects.nonNull(userAllocationStatisticsListDTO)) {
//                x.setAllocationCount(userAllocationStatisticsListDTO.getAllocationCount());
//                x.setAllocationTime(userAllocationStatisticsListDTO.getAllocationLatestTime());
//            }
//        });
//        // 创建工作簿
//        Workbook workbook = new XSSFWorkbook();
//        // 创建工作表
//        Sheet sheet = workbook.createSheet("Sheet1");
//
//        // 创建标题行
//        Row headerRow = sheet.createRow(0);
//        // 设置表头
//        headerRow.createCell(0).setCellValue("用户id");
//        headerRow.createCell(1).setCellValue("渠道来源");
//        headerRow.createCell(2).setCellValue("手机号");
//        headerRow.createCell(3).setCellValue("注册时间");
//        headerRow.createCell(4).setCellValue("分配时间");
//        headerRow.createCell(5).setCellValue("分配次数");
//
//        // 填充数据 从第二行开始
//        int rowNum = 1;
//        for (UserInfoPageDTO dto : list) {
//            // 将Date对象格式化为指定格式的字符串
//            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String registerTime = "";
//            String allocationTime = "";
//            if(dto.getRegisterTime()!=null){
//                registerTime  = outputFormat.format(dto.getRegisterTime());
//
//            }
//            if(dto.getAllocationTime()!=null){
//                 allocationTime = outputFormat.format(dto.getAllocationTime());
//            }
//            // 将Date对象格式化为指定格式的字符串
//            Row row = sheet.createRow(rowNum);
//            row.createCell(0).setCellValue(dto.getId());
//            row.createCell(1).setCellValue(dto.getChannelName());
//            row.createCell(2).setCellValue(dto.getUserPhone());
//            row.createCell(3).setCellValue(registerTime);
//            row.createCell(4).setCellValue(allocationTime);
//            if(dto.getAllocationCount()!=null){
//                row.createCell(5).setCellValue(dto.getAllocationCount());
//            }
//            rowNum ++ ;
//        }
//        // 将工作簿写入 ByteArrayOutputStream
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        workbook.write(byteArrayOutputStream);
//
//        // 设置响应头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentDispositionFormData("attachment", URLEncoder.encode("用户列表", StandardCharsets.UTF_8.toString()) + ".xlsx");
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//
//        // 返回 Excel 文件的字节数组
//        return new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
            return null;
        }
}
